using System;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace ilgolosone.DependencyResolver.Unity
{
    public class UnityControllerFactory : DefaultControllerFactory
    {
        private readonly IUnityContainer _container;

        public UnityControllerFactory(IUnityContainer container)
        {
            _container = container;
        }

        protected override IController GetControllerInstance(Type controllerType)
        {
            if (controllerType == null) return null;
            var controller = _container.Resolve(controllerType) as Controller;
            if (controller == null) 
            {
                throw new ApplicationException(string.Format("Controller non trovato: {0}", controllerType.Name));
            }
            return controller;
        }
    }
}